﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace DatabaseBackup.Library
{
    public class FileHistoryCleanup
    {
        public static void CleanOldFiles(FileType backupType)
        {
            int fileRetentionPeriod = Helpers.RetentionPeriod;
            DirectoryInfo dir = new DirectoryInfo(Helpers.BackupFolder);

            switch (backupType)
            {
                case FileType.DifferentialBackup:
                    // Remove old differential backups
                    FileInfo[] diffFiles = dir.GetFiles("D*.*");

                    foreach (FileInfo f in diffFiles)
                    {
                        DateTime creationTime = f.CreationTimeUtc;

                        if (creationTime < DateTime.UtcNow.Subtract(new TimeSpan(fileRetentionPeriod, 0, 0, 0)))
                        {
                            f.Delete();

                            if (Helpers.FTPEnabled)
                            {
                                AmazonS3Handler.RemoveFile(f.Name);
                            }
                        }

                    }

                    break;

                case FileType.FullBackup:
                    // Remove old full backups
                    FileInfo[] fullFiles = dir.GetFiles("F*.*");

                    foreach (FileInfo f in fullFiles)
                    {
                        DateTime creationTime = f.CreationTimeUtc;

                        if (creationTime < DateTime.UtcNow.Subtract(new TimeSpan(fileRetentionPeriod, 0, 0, 0)))
                        {
                            f.Delete();

                            if (Helpers.FTPEnabled)
                            {
                                AmazonS3Handler.RemoveFile(f.Name);
                            }
                        }
                    }

                    break;

                case FileType.TransactionLogBackup:
                    // Remove old transaction logs
                    FileInfo[] tranFiles = dir.GetFiles("T*.*");

                    foreach (FileInfo f in tranFiles)
                    {
                        DateTime creationTime = f.CreationTimeUtc;

                        if (creationTime < DateTime.UtcNow.Subtract(new TimeSpan(fileRetentionPeriod, 0, 0, 0)))
                        {
                            f.Delete();

                            if (Helpers.FTPEnabled)
                            {
                                AmazonS3Handler.RemoveFile(f.Name);
                            }
                        }
                    }
                    break;
            }
        }
    }

    public enum FileType
    {
        FullBackup = 1,
        DifferentialBackup,
        TransactionLogBackup
    }
}
